﻿using MediatR;
using MyRabbit.Application.Command.ImgCommand;
using MyRabbit.Application.Dtos;
using MyRabbit.Application.ErrorCode;
using MyRabbit.Domain;
using MyRabbit.Repositories;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MyRabbit.Application.CommandHandler.ImgCommandHandler
{
    public class ImgQueryCommandHandler : IRequestHandler<ImgQueryCommand, APIResult<List<ImgDTO>>>
    {

        /// <summary>
        /// 图片仓储
        /// </summary>
        private readonly IRepository<ImgInfo> imgInfoRep;
        /// <summary>
        /// 多图片仓储
        /// </summary>
        private readonly IRepository<ImgInfos> imgInfosRep;
        /// <summary>
        /// 产品仓储
        /// </summary>
        private readonly IRepository<Product> proRep;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="imgInfoRep"></param>
        /// <param name="imgInfosRep"></param>
        /// <param name="proRep"></param>
        public ImgQueryCommandHandler(IRepository<ImgInfo> imgInfoRep, IRepository<ImgInfos> imgInfosRep, IRepository<Product> proRep)
        {
            this.imgInfoRep = imgInfoRep;
            this.imgInfosRep = imgInfosRep;
            this.proRep = proRep;
        }

        /// <summary>
        /// 处理查询命令
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<APIResult<List<ImgDTO>>> Handle(ImgQueryCommand request, CancellationToken cancellationToken)
        {
            APIResult<List<ImgDTO>> result = new APIResult<List<ImgDTO>>();
            result.Code = Codes.查询成功;
            result.Message = Codes.查询成功.ToString();

            var list = from a in await imgInfoRep.GetAllAsync()
                       join b in await imgInfosRep.GetAllAsync() on a.ImgId equals b.ImgId
                       join c in await proRep.GetAllAsync() on b.TheRestId equals c.ProductId
                       where c.ProductId == request.TheRestId
                       select new ImgDTO
                       {
                           Id = a.ImgId,
                           Name = c.ProductName,
                           Url = a.ImgName,
                       };

            result.Data = list.ToList();

            return await Task.FromResult(result);
        }
    }
}
